<template>
	<view @click="openFile()">
		<slot></slot>
	</view>
	<importListVue ref="showList"/>
</template>

<script setup>
	import importListVue from "@/components/setting/importList.vue"
	const showList=ref()
	// #ifdef APP-PLUS
	import {
		createNewFile,
		openFileTool,
		readFileData
	} from "@/uitls/androidTool.js"
	// #endif
	import {
		myShowToast,
		dateTypeFormat
	} from "@/uitls/tool.js"
	import {
		ref
	} from "vue"
	import store from "@/store/index.js"
	let now = dateTypeFormat("YYYY-mm-dd", new Date)
	let getFile = ref()
	const openFile = () => {
		uni.showModal({
			title: '提示',
			content: "导入记录操作将覆盖先有记录",
			success: function(res) {
				if (res.confirm) {
					// #ifdef APP-PLUS
					plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, async function(fs) {
							openFileTool().then((res) => {
								getFile.value = res
								readFileAndroid()
							})
						},
						function(e) {
							myShowToast("请先允许文件读取权限")
						});
					// #endif
					// #ifdef H5
					readFileH5()
					// #endif
				} else if (res.cancel) {}
			}
		});
	}
	const readData = ref()
	const readFileAndroid = async () => {
		let dot = getFile.value.lastIndexOf(".")
		let fen = getFile.value.lastIndexOf("/")
		let name = getFile.value.substring(fen + 1, dot)
		let fileClass = getFile.value.substring(dot + 1, getFile.value.length)
		if (fileClass == 'txt') {
			readData.value = await readFileData(getFile.value)
			setNewAllData(readData.value)
		} else {
			myShowToast("文件类型错误")
		}
	}
	const readFileH5 = async () => {
		if ('showOpenFilePicker' in self) {
			const pickerOpts = {
				types: [{
					description: 'Text files',
					accept: {
						'text/plain': ['.txt'],
					},
				}],
				excludeAcceptAllOption: true,
				multiple: false,
			};
			window.showOpenFilePicker(pickerOpts).then(async(result) => {
				let file=await result[0].getFile()
				// 处理选择的文件
				let fr=new FileReader()
				fr.onload=function(res){
					readData.value=event.target.result
					setNewAllData(readData.value)
				}
				fr.readAsText(file);
			});
		}
	}
	function isJson(data) {
	    try {
	        JSON.parse(data);
	    } catch (e) {
	        return false;
	    }
	    return true;
	}
	const setNewAllData=(data)=>{
		if(isJson(data)){
			let jsonData= JSON.parse(data)
			if('tag' in jsonData && jsonData.tag=="AccountBook"){
				showList.value.open(jsonData)
				store.state.mainData.allData = jsonData
				store.commit("mainData/updateData")
				myShowToast("导入记录成功")
			}else{
				myShowToast("导入数据错误")
			}
		}else{
			myShowToast("导入数据出错")
		}
		
	}
</script>

<style lang="scss">

</style>